#pragma once
#include "Sqlite3Manager.hpp"

#define SQL_SIZE 256


class AutoGetResTable
{
public:
	AutoGetResTable(Sqlite3Manager* sm, char sql[], char**& ppRst, int& row, int& col) :_prst(nullptr)
	{
		sm->GetResultTable(sql, ppRst, row, col);
		_prst = ppRst;
	}

	~AutoGetResTable()
	{
		if (_prst)
		{
			sqlite3_free_table(_prst);
			_prst = nullptr;
		}
	}
private:
	char** _prst;
};

class DataManager
{
private:
	Sqlite3Manager _sm;

private:
	void InitSqlite()
	{
		char sql[SQL_SIZE] = { 0 };
		sprintf(sql, "CREATE TABLE if not exists %s (\
					  doc_name text,\
			          doc_path text);"
			, "doc_info");

		_sm.Exec(sql);
	}

public:
	DataManager()
	{
		_sm.Open(".\\doc_sys.db");
		InitSqlite();
	}


	void InsertDoc(const string& docName, const string& docPath)
	{
		char sql[SQL_SIZE] = { 0 };
		sprintf(sql, "INSERT INTO %s VALUES('%s','%s');" 
			, "doc_info", docName.c_str(), docPath.c_str());

		_sm.Exec(sql);
	}

	void DeleteDoc(const string& docName, const string& docPath)
	{
		char sql[SQL_SIZE] = { 0 };
		sprintf(sql, "DELETE FROM %s WHERE doc_name='%s'AND doc_path='%s';"
			, "doc_info", docName.c_str(), docPath.c_str());

		_sm.Exec(sql);
	}

	void Search(const string& key,vector<pair<string,string>>& docNamePath )
	{
		char sql[SQL_SIZE] = { 0 };
		sprintf(sql, "SELECT * FROM %s WHERE doc_name LIKE '%%%s%%';"
			, "doc_info",key.c_str());

		char** Rest = nullptr;
		int row = 0;
		int col = 0;

		AutoGetResTable aGRT(&_sm, sql, Rest, row, col);

		for (int i = 1; i <= row; ++i)
		{
			docNamePath.push_back(make_pair(*(Rest + i * col + 0),*(Rest + i * col + 1)));
		}
	}

	void GetDoc(multiset<string>& DbdocInfo)
	{
		char sql[SQL_SIZE] = { 0 };
		sprintf(sql, "SELECT * FROM %s;"
			         , "doc_info");

		char** ppRest = nullptr;
		int row = 0;
		int col = 0;
		AutoGetResTable aGRT(&_sm, sql, ppRest, row, col);
 
		for (int i = 1; i <= row; ++i)
		{
			DbdocInfo.insert(*(ppRest + i * col + 0));
		}

	}

	~DataManager()
	{
		_sm.Close();
	}
};

